$(() => {
  // 监听消息传递
  chrome.extension.onMessage.addListener(
    function (req, sender, res) {
      if (req.action === 'completed') {
        //页面加载完毕
        if(/^https:\/\/detail\.tmall\.com\/item.htm/.test(req.url)){
          $('html,body').animate({ scrollTop: document.body.scrollHeight }, 1000)
          setTimeout(() => {
            getDetail(req)
          }, 1000)
        }else if(/^https:\/\/.+\.tmall\.com\/(search\.htm|category.*\.htm|.+scene=taobao_shop)/.test(req.url)){
          window.scrollTo(0, document.body.scrollHeight)
          getList(req, res)
        }
      }
      // 一定要 return
      return true
    }
  )
})


// 获取商品列表以及sku
function getList() {
  if (/^https:\/\/.+\.tmall\.com\/(search\.htm|category.*\.htm|.+scene=taobao_shop)/.test(location.href)) {
    // 通用模板
    var productList = []
    var dl = $('.item')
    var flag = true
    let timer = setInterval(function(){
      if (dl.length > 0) {
        clearInterval(timer)
        dl.each(function() {
          if (productList.length > 0) {
            productList.forEach(product => {
              if ('tmall_' + $(this).attr('data-id') === product[0].id) flag = false
            })
            flag ? productList.push([{ id: 'tmall_' + $(this).attr('data-id'), url: $(this).find('.photo a').attr('href') }]) : null
          } else {
            productList.push([{ id: 'tmall_' + $(this).attr('data-id'), url: $(this).find('.photo a').attr('href') }])
          }
        })
        // 判断是否有分页组件 没有则end
        var pagination = $('.pagination a')
        if (pagination && pagination.length > 0) {
          if ($(pagination[pagination.length - 1]).attr('class') === 'disable') {
            // 最后一页
            sendMsg({ data: productList }, 'end')
          } else {
            sendMsg({ data: productList, url: $(pagination[pagination.length - 1]).attr('href') }, 'next')
          }
        } else {
          sendMsg({ data: productList }, 'end')
        }
      }
    },1000)
  } else {
    console.log('not found')
  }

}

var detailInfo = new Object()

// 获取sku数据
function getDetail() {

  if (/^https:\/\/detail\.tmall\.com\/item.htm/.test(location.href)) {
    // 主图
    detailInfo.images = []
    let scrollImages = $('#J_UlThumb li')
    if(scrollImages.length > 0) {
      scrollImages.each(function(i) {
        if (i < 5) {
          detailInfo.images.push({ imageURL: $(this).find('img').attr('src').replace('60x60', '430x430'), isMain: i === 0 ? true : false , sort: i, streamMediaType: 'IMG'})
        }
      })
    }

    console.log('获取天猫商品详情')
    try {
      var skuOuterHTML = $('#J_DetailMeta .tm-clear>script')[3].outerHTML.trim().split('TShop.Setup(')[1].split('</script>')[0].trim().split('})();')[0].trim()
      var skuInfo = JSON.parse(skuOuterHTML.substring(0, skuOuterHTML.length - 2))
      if (skuInfo.itemDO) {
        detailInfo.title = skuInfo.itemDO.title // 标题
        detailInfo.brand = skuInfo.itemDO.brand // 品牌
        detailInfo.weight = 1 // 最小起定量

        // 报价方式
        if (skuInfo.itemDO.hasSku) {
          // 按规格
          detailInfo.quoteMode = 'SPECIFICATIONS'
          detailInfo.specifications = []
          var skuList = skuInfo.valItemInfo.skuList.map(list => {
            let info = {}
            for (let i in skuInfo.valItemInfo.skuMap) {
              if (list.skuId === skuInfo.valItemInfo.skuMap[i].skuId) {
                info = skuInfo.valItemInfo.skuMap[i]
                break
              }
            }
            delete info.skuId
            return { ...list, ...info }
          })
          var skuValue = []
          detailInfo.productSpecifications = skuList.map(sku => {
            let values = sku.pvs.split(';')
            if (values.length > 1) {
              sku.names = sku.names.split(' ').filter(name => {
                return name && name.trim()
              })
            } else {
              sku.names = [sku.names.trim()]
            }
            let nameObj = {}
            sku.names.forEach((name, index) => {
              nameObj['name' + index] = name
              if (skuValue.length > 0) {
                let flag = true
                for (let i in skuValue) {
                  if (skuValue[i].value === values[index]) {
                    flag = false
                    break
                  }
                }
                if (flag) skuValue.push({ name: name, value: values[index] })
              } else {
                skuValue.push({ name: name, value: values[index] })
              }
            })
            return { names: sku.names, value: sku.names.join(','), sellingPrice: sku.priceCent / 100, ...nameObj, distributionAmount: 0, inventory: sku.stock }
          })
          let props = $('.tb-sku .tm-sale-prop .J_TSaleProp')
          if (props.length > 0) {
            props.each(function() {
              let values = []
              const PROPS_SELF = this
              $(PROPS_SELF).find('li').each(function() {
                let value = skuValue.filter(v => v.value === $(this).attr('data-value'))
                values.push({
                  icon: $(PROPS_SELF).attr('class').indexOf('tb-img') !== -1 && $(this).find('a').attr('style') ? $(this).find('a').attr('style').split('background:url(')[1].split(')')[0] : '',
                  value: value[0].name
                })
              })
              detailInfo.specifications.push({
                name: $(PROPS_SELF).attr('data-property') || '',
                values: values
              })
            })
          }
        } else {
          // 按数量
          detailInfo.quoteMode = 'NUMBERS'
          detailInfo.numbersQuote = {
            inventory: $('#J_EmStock').text().replace(/[^0-9]/ig, ''),
            numbersQuotes: [{
              startNumber: 1,
              price: $('#J_PromoPrice .tm-price').text() || parseFloat(skuInfo.itemDO.reservePrice)
            }]
          }
        }

        // 商品规格详情介绍
        let parameterList = []
        $('#J_AttrUL li').each(function(i) {
          parameterList.push($(this).text())
        })
        detailInfo.productSourceInfo = {
          url:location.href,
          title: detailInfo.title,
          name: '产品参数',
          props: parameterList,
          specs: []
        }
        
        // 来源
        detailInfo.productSourceType = '1'

        // 详情图片
        
        let timer = setInterval(function() {
          if ($('#description .content').text().trim() !== '描述加载中') {
            let html = $('#description .content')
            html.find('img').each(function() {
              if ($(this).attr('class') !== 'img-ks-lazyload') {
                let lazyload = $(this).attr('data-ks-lazyload')
                if (lazyload) $(this).attr('src', lazyload)
              }
            })
            detailInfo.info = html.html()
            clearInterval(timer)
            sendMsg(detailInfo, 'upload')
          }
        },1000)
      }
    }
    catch(error) {
      console.log('获取详情失败---->>>>' + error)
    }

  }

}

// 将获取内容传递给后台脚本进行处理
function sendMsg(msg, cmd) {
　　chrome.extension.sendMessage({ 'msg': msg, 'cmd': cmd })
}
